<!--
 * @author hugh
 * @time  2021-01-10 11:40
 * @title  首页
 * @desc
 -->
<template>
  <div class="pages home">
    <el-row class="heigth-fill">
      <el-col :span="data.showMenus ? 3 : 0" class="heigth-fill bg-theme-dark">
        <LeftMenu :active="menuActive" :datas="data.menuslist" @header="toRouter" @select="selectItem" @open="handleOpen" @close="handleClose"></LeftMenu>
      </el-col>
      <el-col :span="data.showMenus ? 21 : 24" class="heigth-fill">
        <div class="grid-content heigth-fill">
          <el-container>
            <el-header class="border-bottom flex justify-between bg-theme-dark">
              <Header :menus="data.tabs" :active="data.tabSelectindex" :restaurants="data.restaurants" @tabclick="handleClick" @select="handleSelect" @leftmenu="onShowMenus"></Header>
            </el-header>
            <el-main class="no-padding">
              <div class="scrollView" @scroll="toScroll" :style="{ height: data.conentHeight + 'px' }">
                <div class="affix-box">
                  <div class="padding-sm">
                    <el-breadcrumb separator-class="el-icon-arrow-right">
                      <el-breadcrumb-item v-for="(item, index) in data.headers" :key="index">{{ item.name }}</el-breadcrumb-item>
                    </el-breadcrumb>
                  </div>
                  <el-tabs v-model="data.editableTabsValue" type="card" closable @tab-remove="handleTabsEdit" @tab-click="handTabClick">
                    <el-tab-pane label="首页" name="/statistics"></el-tab-pane>
                    <el-tab-pane v-for="(item, index) in data.editableTabs" :key="index" :label="item.name" :name="item.menuId + ''"></el-tab-pane>
                  </el-tabs>
                </div>
                <div class="content-box">
                  <transition name="el-fade-in-linear"><router-view></router-view></transition>
                </div>
              </div>
            </el-main>
          </el-container>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, getCurrentInstance, toRefs, reactive, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';
import LeftMenu from '@/components/Menu/Menu.vue';
import Header from '@/components/Menu/Header.vue';
import { AppModule } from '@/store/modules/app';

//路由
const router = useRouter();
//vuex
const store = useStore();
//绑定挂载全局对象
const { proxy } = getCurrentInstance() as any;
const { login, menulists } = proxy.$api.Other;
store.commit('getClients');

const baseMenu: any = store.state.menu;
let menuCheck = store.state.menuCheck;
//定义参数集合
const data = reactive({
  conentHeight: store.state.conentHeight,
  user: store.state.clients.user,
  restaurants: [baseMenu],
  showMenus: true,
  tabs: [
    {
      name: '数据',
      css: 'eleme'
    },
    {
      name: '系统',
      css: 'eleme'
    },
    {
      name: '运营',
      css: 'eleme'
    },
    {
      name: '其他',
      css: 'eleme'
    }
  ],
  menuslist: store.state.menuslist,
  editableTabs: store.state.editableTabs,
  headers: store.state.headers,
  editableTabsValue: store.state.editableTabsValue,
  tabSelectindex: store.state.tabSelectindex,
  menuActive: store.state.menuActive
});
const route = useRoute();
watch(
  () => route.path,
  () => {
    console.log('监听到变化');
    data.editableTabsValue = store.state.editableTabsValue;
    data.editableTabs = store.state.editableTabs;
    data.menuActive = store.state.menuActive;
    data.headers = store.state.headers;
    menuCheck = store.state.menuCheck;
  }
);
onMounted(() => {
  onLoadStorage();
});
onUnmounted(() => {
  localStorage.removeItem('headers');
  localStorage.removeItem('editableTabs');
  localStorage.removeItem('editableTabsValue');
  localStorage.removeItem('menuActive');
  localStorage.removeItem('keyStr');
});
/**
 * 初始化页面
 */
function initPage() {
  localStorage.removeItem('keyStr');
  data.headers = [baseMenu];
  data.editableTabs = [];
  data.editableTabsValue = '0';
  data.menuActive = baseMenu.id.toString();
  menuCheck = [baseMenu.menuId];
}
/**
 * 路由跳转
 */
function toRouter(path: string) {
  router.push(path);
  if (path === '/statistics') {
    initPage();
  }
}
/**
 * 查找菜单项
 */
let keys: any = [];
let pathStr: string = '';
function findMenu(lists: any, keyStr: string, index: number, status: Boolean) {
  if (index === 0) {
    keys = keyStr.split('_');
    data.headers = [];
    pathStr = '';
  }
  if (keys.length === index) {
    //点击回首页
    return;
  }
  let key: number = parseInt(keys[index]);
  lists[key].open = true;
  pathStr += lists[key].path;
  data.headers[index] = lists[key];
  index += 1;
  if (index < keys.length && lists[key].childs) {
    findMenu(lists[key].childs, keyStr, index, status);
  } else {
    //找到最下级
    if (status) {
      localStorage.setItem('keyStr', keyStr);
      setRouter(lists[key], pathStr);
    }
  }
}
/**
 * 保存当前路由状态
 */
function saveRouterState() {
  localStorage.setItem('headers', JSON.stringify(data.headers));
  localStorage.setItem('editableTabs', JSON.stringify(data.editableTabs));
  localStorage.setItem('editableTabsValue', data.editableTabsValue);
  localStorage.setItem('menuActive', data.menuActive);
  store.commit('setMenusList', data.menuslist);
  store.commit('setEditableTabs', data.editableTabs);
  store.commit('setHeaders', data.headers);
  store.commit('setMenuCheck', menuCheck);
  store.commit('setEditableTabsValue', data.editableTabsValue);
  store.commit('setTabSelectindex', data.tabSelectindex);
  store.commit('setMenuActive', data.menuActive);
}
/**
 * 设置路由
 */
function setRouter(tab: any, pathStr: string) {
  if (pathStr) {
    let index = menuCheck.indexOf(tab.menuId);
    if (index == -1) {
      data.editableTabs.push(tab);
      menuCheck.push(tab.menuId);
    }
    data.editableTabsValue = tab.menuId.toString();
    data.menuActive = tab.id.toString();
    saveRouterState();
    toRouter(pathStr);
  }
}
/**
 * 菜单打开
 * @param key  点击标记
 * @param keyPath 点击路径
 */
function handleOpen(key: any, keyPath: any) {
  findMenu(data.menuslist, key, 0, false);
}
/**
 * 菜单关闭
 * @param key  点击标记
 * @param keyPath 点击路径
 */
function handleClose(key: any, keyPath: any) {
  // console.log(key, keyPath);
}

/**
 * 标签选择
 * @param key  点击标记
 * @param keyPath 点击路径
 */
function selectItem(key: string, keyPath: any) {
  findMenu(data.menuslist, key, 0, true);
}

/**
 * 刷新登录用户
 */
function onRefreshToken() {
  onLoadMenu();
}
/**
 * 设置页面路径
 */
function setPageMenu(index: number) {
  data.tabSelectindex = index;
  localStorage.setItem('tabSelectindex', index.toString());
  store.commit('setMenusList', data.menuslist);
  // if (index == 0) {
  //   let keyStr = localStorage.getItem('keyStr');
  //   if (keyStr) {
  //     findMenu(data.menuslist, keyStr, 0, true);
  //   } else {
  //     let frist = data.menuslist[0].childs[0];
  //     findMenu(data.menuslist, frist.id, 0, true);
  //   }
  // }
}
/**
 * 加载菜单栏
 */
function onLoadMenu() {
  menulists({ type: 1 })
    .then((res: any) => {
      data.menuslist = proxy.$setTreeList(res);
      setPageMenu(data.tabSelectindex);
    })
    .catch((err: any) => {
      console.log(err);
    });
}

/**
 * 移除菜单标签
 */
function handleTabsEdit(target: any, action: string) {
  let index = menuCheck.indexOf(parseInt(target));
  if (index !== -1) {
    if (index >= 1) {
      findMenu(data.menuslist, data.editableTabs[index - 1].id, 0, true);
    }
    data.editableTabs.splice(index, 1);
    menuCheck.splice(index, 1);
    store.commit('setMenuCheck', menuCheck);
    store.commit('setEditableTabs', data.editableTabs);
  }
}
/**
 * 点击菜单标签
 */
function handTabClick(target: any, action: string) {
  if (target.props.name === '/statistics') {
    toRouter(target.props.name);
    return;
  }
  if (target.props.name) {
    let index = menuCheck.indexOf(parseInt(target.props.name));
    if (index !== -1 && data.editableTabs[index].id) {
      findMenu(data.menuslist, data.editableTabs[index].id, 0, true);
    }
  }
}

/**
 * 加载页面缓存
 */
function onLoadStorage() {
  let headers = localStorage.getItem('headers');
  if (headers) {
    data.headers = JSON.parse(headers);
  } else {
    data.headers = [baseMenu];
  }
  let editableTabs = localStorage.getItem('editableTabs');
  if (editableTabs) {
    menuCheck = [];
    data.editableTabs = JSON.parse(editableTabs);
    for (let i = 0, len = data.editableTabs.length; i < len; i++) {
      menuCheck.push(data.editableTabs[i].menuId);
    }
  } else {
    data.editableTabs = [];
  }
  let editableTabsValue = localStorage.getItem('editableTabsValue');
  if (editableTabsValue) {
    data.editableTabsValue = editableTabsValue;
  } else {
    data.editableTabsValue = '0';
  }
  let menuActive = localStorage.getItem('menuActive');
  if (menuActive) {
    data.menuActive = menuActive;
  } else {
    data.menuActive = '';
  }

  let tabSelectindex = localStorage.getItem('tabSelectindex');
  if (tabSelectindex) {
    data.tabSelectindex = parseInt(tabSelectindex);
  } else {
    data.tabSelectindex = 0;
  }
  saveRouterState();
  onRefreshToken();
}
/**
 * 检索列表点击
 */
const handleSelect = (item: any) => {
  findMenu(data.menuslist, item.id, 0, true);
};
/**
 * 根据id跳转路由
 */
const handleClick = (index: any) => {
  initPage();
  setPageMenu(parseInt(index));
}
const onShowMenus = (state: any) => {
  data.showMenus = state;
}

const toScroll = (event: any) => {
  console.info(event);
}
</script>
<style scoped>
.scrollView {
  width: 100%;
  overflow-y: scroll;
  padding: 0 0.75rem 0.75rem 0.75rem;
}

.affix-box {
  padding: 0 0.75rem 0.75rem 0.75rem;
  background-color: #fff;
  position: -webkit-sticky;
  position: sticky;
  top: 0px;
  z-index: 1000;
}
</style>
